<template>
  <div class="main">
    <div class="form_content">
      <NScrollbar>
        <div class="content" style='padding-top:100rem'>
          <NSpace>
            <DetailFormProvider>
            <NForm ref="formRef" :model="formValue" :rules="rules" label-placement="left" :label-width="115"
              label-align="right" :disabled="disabled" require-mark-placement="left">
              <NSpace justify="space-between">
                <NFormItem label="标签:" path="tagName">
                  <NInput v-model:value="formValue.tagName" placeholder="输入标签" style="width: 250px" />
                </NFormItem>
                <NFormItem
                label="标签用途"
                path="tagUseCode"
              >
                <NSelect
                  :options="labelOptions"
                  v-model:value="formValue.tagUseCode"
                  placeholder="请选择藏品标签"
                  clearable
                  style="width: 250px"
                />
              </NFormItem>
              </NSpace>
              <NSpace>
                <NFormItem label="备注:" path="remark">
                  <NInput v-model:value="formValue.remark" placeholder="输入备注" style="width: 630px" type="textarea" />
                </NFormItem>
              </NSpace>
            </NForm>
          </DetailFormProvider>
          </NSpace>
        </div>
      </NScrollbar>
    </div>
  </div>
  <FixedAction>
    <NSpace justify="center">
      <NButton style="width: 78px" ghost @click="goBack">
        取消
      </NButton>
      <NButton v-if="!disabled" type="primary" style="width: 78px" @click="confirm" :disabled="loading"
        :loading="loading">
        保存
      </NButton>
    </NSpace>
  </FixedAction>
</template>

<script setup lang="ts">
import { ref, onMounted, reactive, watch } from 'vue'
import {
  NSpace,
  NForm,
  NInput,
  NFormItem,
  NButton,
  NScrollbar,
  useMessage,
  NSelect,
} from 'naive-ui'
import type { FormInst } from 'naive-ui'
import router from '@/router'
import { useRoute } from 'vue-router'
import { useTagStore } from '@/stores/layout'
import FixedAction from '@/components/FixedAction.vue'
import { sendRequest } from '@/utils/api'
import { keysOf } from '@/utils/object'
import type { HttpResponse } from '@/utils/http'
import useRouteReplace from '@/hooks/useRouteReplace'
const tags = useTagStore().tags
const message = useMessage()
const loading = ref(false)
const route = useRoute()
const disabled = ref(route.name == 'LabelConfigDetail')
const isEdit = ref(route.name == 'LabelConfigEdit')
const formRef = ref<FormInst | null>(null)
const formValue = reactive({
  tagName: '',
  tagUseCode: '',
  remark: ''
})
const routeReplace = useRouteReplace(route.query.redirect as string)
const rules = {
  tagName: {
    required: true,
    trigger: ['input', 'blur', 'change'],
    validator: (_: any, value: any) => {
      if (value.length == 0) return new Error('请输入标签')
      if (value.length > 20) return new Error('标签字数不得超过20')
      return true
    }
  },
  tagUseCode:{
    required: true,
    trigger: ['input', 'blur', 'change'],
    validator: (_: any, value: any) => {
      if (!value) return new Error('请选择标签用途')
      return true
    }
  },
  remark: {
    required: false,
    trigger: ['input', 'blur', 'change'],
    validator: (_: any, value: any) => {
      if (value.length > 500) return new Error('备注字数不得超过500')
      return true
    }
  },
}
// 返回
const goBack = () => {
  const index = tags.findIndex((item: any) => item.path === router.currentRoute.value.fullPath)

  tags.splice(index, 1)
  if (tags.length == 0) {
    router.push({ path: '/OA/Workbench/UserDesktop' })
  } else history.back()
}

//修改
const confirm = () => {
  formRef.value?.validate(async (err: any) => {
    if (err) return
    loading.value = true
    const [error, res] = await sendRequest<HttpResponse>({
      module: 'labelConfig',
      api: !isEdit.value ? 'save' : 'update',
      override: {
        data: {
          ...formValue,
          id:!isEdit.value ?null: route.params.id 
        }
      }
    })
    loading.value = false
    if (error) return message.error(error.message)
    message.success(res.msg)
    routeReplace()
    // goBack()
  })
}
// 版本类型下拉框
const versionTypeOptions = ref([])
const versionTypeLoading = ref(false)
// 如果 childList是空数组，则此节点是leaf为true的节点，并且把childList置为undefined
const handleVersionOptionsLeaf = (options: any[]) => {
  options.forEach((e) => {
    if (e.childList?.length) {
      handleVersionOptionsLeaf(e.childList)
    } else {
      e.isLeaf = true
      e.childList = undefined
    }
  })
  return options
}
const queryVersionTypeOptions = async () => {
  versionTypeLoading.value = true
  try {
    const [error, res] = await sendRequest({
      module: 'collector',
      api: 'versionListTreeAll',
      override: {
        params: {
          statusCode: 'A4901'
        }
      }
    })

    if (error) throw error
    if (res.code !== 0) throw new Error(res.msg)
    handleVersionOptionsLeaf(res.data as unknown as VersionOption[])
    versionTypeOptions.value = res.data.length ? res.data : []
  } catch (error) {
    console.error(error)
  } finally {
    versionTypeLoading.value = false
  }
}
const handleVersionSelectLoad = async (option: any) => {
  const child = await queryVersionTypeOptions(option.value as string)
  if (!child) option.isLeaf = true
  option.children = child
}
// 获取详情
const spinShow = ref(false)
const getDispatchInfo = async () => {
  spinShow.value = true
  const [error, res] = await sendRequest<HttpResponse>({
    module: 'labelConfig',
    api: 'info',
    uri: {
      id: route.params.id as never
    }
  })
  if (error) return message.error(error.message)
  if (res.code !== 0) return message.error(res.msg)
  keysOf(res.data).forEach((e) => {
    // @ts-ignore
    formValue[e] = res.data[e]
  })
  spinShow.value = false
}
const labelOptions = ref([])
const getLabelOptions = async () => {
  const [error, res] = await sendRequest<HttpResponse>({
    module: 'baseDonateCertificate',
    api: 'listByParentCode',
    override: {
      params: {
        dicCode: 'A69'
      }
    }
  })
  if (error) return message.error(error.message)
  res.data.forEach((i: any) => {
    // @ts-ignore
    labelOptions.value.push({ label: i.dicName, value: i.dicCode })
  })
}
const getLabelConfig = async () => {
  const [error, res] = await sendRequest<HttpResponse>({
    module: 'labelConfig',
    api: 'getDefaultUseCode',
  })
  if (error) return message.error(error.message)
  formValue.tagUseCode = res.data
}
watch(
  () => route,
  () => {
    if (route.name == 'LabelConfigDetail' || route.name == 'LabelConfigEdit') {
      getDispatchInfo()
     disabled.value = route.name == 'LabelConfigDetail'
    isEdit.value = route.name == 'LabelConfigEdit'
    }
    else{
      isEdit.value=false
      disabled.value=false
      formValue.tagName=''
      formValue.tagUseCode=''
      formValue.remark=''
      getLabelConfig()
    }
  },
  { deep: true, immediate: true }
)
onMounted(() => {
  queryVersionTypeOptions()
  getLabelOptions()
})

</script>

<style scoped lang="scss">
@mixin CommonFont {
  font-size: 16rem;
  font-family: PingFangSC, PingFang SC;
  font-weight: 400;
  color: rgba(0, 0, 0, 0.85);
}

.commonWidth {
  width: 360rem;
}

.main {
  display: flex;
  flex-direction: column;
  width: 100%;
  height: 100%;
  overflow: hidden;

  .topTitle {
    width: 100%;
    height: 64rem;
    border-bottom: 1px solid #fff;
    padding: 20rem;
    margin-bottom: 20rem;
    @include CommonFont;
  }

  .form_content {
    width: 100%;
    height: 100%;
    padding: 20rem 20rem 0;

    .content {
      display: flex;
      align-items: center;
      flex-direction: column;
      width: 100%;
      height: 100%;
      padding: 18rem 33rem 120rem;
      overflow-y: scroll;
      background-color: #ebeceb;

      .scope {
        width: 360rem;
        height: 130rem;
        background: #e1e1e1;
        margin-bottom: 25rem;
      }
    }
  }
}

.content::-webkit-scrollbar {
  display: none;
}

:deep(.n-spin-container) {
  width: 100%;
  height: 100%;
}

:deep(.n-scrollbar-container) {
  width: 100%;
  height: 100%;
}

:deep(.n-scrollbar-content) {
  width: 100%;
  height: 100%;
}

:deep(.n-spin-content) {
  width: 100%;
  height: 100%;
}
</style>
